package com.scopionstudio.djnonstop;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.analytics.tracking.android.EasyTracker;
import com.scopionstudio.adapter.AdapterListMain;
import com.scopionstudio.bean.ItemsMusic;
import com.scopionstudio.network.NetWork;
import com.scopionstudio.utils.DatabaseHandler;
import com.scopionstudio.utils.GifDecoder;
import com.scopionstudio.utils.JsonParser;

public class MainMusicActivity extends Activity implements OnClickListener, OnCompletionListener, OnBufferingUpdateListener {
    private static final String DJ_LINK_PART = "http://app.zigma.vn/music/nonstop/?page=";
    private static final String ROOT_JSON = "nonstop";
    private static final String DETAIL_TAG_JSON = "nonstopdetail";
    private static final String URL = "url";
    private static final String NAME = "name";
    private static final String DETAIL = "detail";
    private static final String ORDER = "order";
    private int currentPage = 2;
    private ImageView mButton, mbtnNext, mbtnPreview, imvReload;
    private ImageView mbtnUpdateList;
    private MediaPlayer mediaPlayer;
    private ProgressDialog proGress;
    private ProgressDialog pDialog;
    private static ArrayList<ItemsMusic> itemsMusic;
    //private AdapterListMain menuAdapter;
    private ItemsMusic mItemsMusic;
    private JSONArray mJsonArray = null;
    private MyTask mTask = null;
    private final Handler handler = new Handler();
    private ListView mListView;
    private AdapterListMain mAdapter;
    private TextView mTextView;
    private int ID_PLAY = 0;
    private int ID_LIST_MAX = 0;
    private int ID_CHECK_FIRST = -1000;
    //	private QuickAction quickAction;
    private String linkCurrent = "";
    DatabaseHandler mHandler;
    private NetWork mNetWork = new NetWork(this);
    int textlength = 0;
    private Context context;
    private Runnable notification;
    // Action item
    private AdView adView;
    private boolean CHECK_CLICK = false;
    private loadURL ansLoadURl = new loadURL();
    private LoadMoreMusic mLoadmore;
    private Animation mAnim360;
    private PlayMusicAnsytask mTaskPlayMusic;
    private boolean mIsPlayingGif = false;

    private GifDecoder mGifDecoder;

    private Bitmap mTmpBitmap;

    final Handler myHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setProgressBarIndeterminateVisibility(true);
        setContentView(R.layout.activity_main_music);
        initVariable();
        initUI();
        try {
            LoadData();
        } catch (Exception e) {
            Log.e("loi load du lieu", e.toString());
        }
        /*
         * Play image gif.
         */
        InputStream stream = null;
        try {
            stream = getAssets().open("girldancingone.gif");
        } catch (IOException e) {
            e.printStackTrace();
        }
        playGif(stream);
    }

    private void LoadData() {
        try {
            if (mNetWork.isOnline() == true) {
                mTask = new MyTask();
                mTask.execute(DJ_LINK_PART + "1");
            } else {
                AlertDialog.Builder mAlert = new AlertDialog.Builder(
                        MainMusicActivity.this);
                mAlert.setTitle("Không có mạng");
                mAlert.setMessage(
                        "Máy bạn hiện không có kết nối mạng, bạn có muốn thử kết nối lại không ?")
                        .setPositiveButton("Có",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        try {
                                            Intent intent = new Intent(Intent.ACTION_MAIN);
                                            intent.setClassName("com.android.settings", "com.android.settings.wifi.WifiSettings");
                                            startActivityForResult(intent, 100);
                                        } catch (Exception ex) {
                                            Log.e("error load", ex.toString());
                                        }
                                    }
                                })
                        .setNegativeButton("Không",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.cancel();
                                        dialog.dismiss();
                                        finish();
                                    }
                                });
                AlertDialog mAlertDialog = mAlert.create();
                mAlertDialog.show();
            }


        } catch (Exception ex) {
            Log.e("error load", ex.toString());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initUI() {

        adView = (AdView) findViewById(R.id.adView);
        adView.loadAd(new AdRequest());
        mButton = (ImageView) findViewById(R.id.btn_play_pause);
        mButton.setOnClickListener(this);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View viewFooter = inflater.inflate(R.layout.layout_footer_listview, null);
        mbtnUpdateList = (ImageView) viewFooter.findViewById(R.id.btn_load_more);
        mbtnUpdateList.setOnClickListener(this);
        mbtnUpdateList.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            	mLoadmore = new LoadMoreMusic();
            	mLoadmore.execute(DJ_LINK_PART + currentPage);
            }
        });
        mbtnNext = (ImageView) findViewById(R.id.btn_next);
        mbtnNext.setOnClickListener(this);
        mbtnPreview = (ImageView) findViewById(R.id.btn_previous);
        mbtnPreview.setOnClickListener(this);
        mTextView = (TextView) findViewById(R.id.tv_show_current_song);
        mTextView.setSelected(true);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.reset();
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                try {
                    if (ID_PLAY + 1 < ID_LIST_MAX - 1) {
                        String urlLoaded = new loadURL().execute(itemsMusic.get(ID_PLAY + 1).getDetail()).get();
                        new PlayMusicAnsytask().execute(urlLoaded);
                        mTextView.setText(itemsMusic.get(ID_PLAY + 1).getName());
                        linkCurrent = urlLoaded;
//                        mButton.setImageResource(R.drawable.btn_pause);
                        ID_PLAY += 1;
                    } else {
                        ID_PLAY = 0;
                        String urlLoaded = new loadURL().execute(itemsMusic.get(0).getDetail()).get();
                        new PlayMusicAnsytask().execute(urlLoaded);
                        mTextView.setText(itemsMusic.get(0).getName());
                        linkCurrent = urlLoaded;
//                        mButton.setImageResource(R.drawable.btn_pause);
                        ID_PLAY += 1;
                    }
                    mButton.startAnimation(mAnim360);

                } catch (Exception e) {
                    Log.e("Error next", e.toString());
                }


            }
        });
        imvReload = (ImageView) findViewById(R.id.iv_logo);
        imvReload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                LoadData();
            }
        });
        // declare variable
        itemsMusic = new ArrayList<ItemsMusic>();
        mItemsMusic = new ItemsMusic();

        //stringListMuic = new String();
        // list view
        mListView = (ListView) findViewById(R.id.list_music);
        //itemsMusic.clear();

        mListView.addFooterView(viewFooter);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                itemMainClick(position);
            }
        });

    }

    public void initVariable() {
        mediaPlayer = new MediaPlayer();
        mHandler = new DatabaseHandler(this);
        mAnim360 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_360);
    }

    private void primarySeekBarProgressUpdater() {

        try {
            if (mediaPlayer.isPlaying()) {
                notification = new Runnable() {
                    public void run() {
                        primarySeekBarProgressUpdater();
                    }
                };
                handler.postDelayed(notification, 1000);
            } else {
            }
        } catch (Exception e) {
            Log.e("error seek bar", e.toString());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_play_pause:
                if (ID_CHECK_FIRST >= 0) {
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
//                        mButton.setImageResource(R.drawable.btn_pause);
                        mButton.startAnimation(mAnim360);

                    } else {
                        mediaPlayer.pause();
//                        mButton.setImageResource(R.drawable.btn_play);
                        mButton.clearAnimation();
                    }
//                    primarySeekBarProgressUpdater();
                } else {
                    Toast.makeText(MainMusicActivity.this, "Hãy chọn bài để nghe !", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_next:
                if(ID_PLAY < mAdapter.getCount()-1){
                    itemMainClick(ID_PLAY + 1);
                }else{
                    Toast.makeText(MainMusicActivity.this, "Không thể thực hiện", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_previous:
                if (ID_PLAY > 0) {
                    itemMainClick(ID_PLAY - 1);
                } else {
                    Toast.makeText(MainMusicActivity.this, "Không thể thực hiện", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    class preViewMusic extends AsyncTask<Integer, Void, Void> {
        int id = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            proGress = new ProgressDialog(MainMusicActivity.this);
            proGress.setMessage("Đợi tí nhé ....");
            proGress.setCancelable(true);
            proGress.setCanceledOnTouchOutside(false);
            proGress.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
//                    mediaPlayer.release();
//                    mediaPlayer = new MediaPlayer();
//                    mButton.setImageResource(R.drawable.btn_play);
                    mButton.clearAnimation();
                    ID_CHECK_FIRST = -10000;
                    ID_PLAY = 2;
                    cancel(true);
                }
            });
            proGress.show();
        }

        @Override
        protected Void doInBackground(Integer... params) {
            id = params[0];
            try {
                mediaPlayer.pause();
                mediaPlayer.reset();
                String urlLoaded = new loadURL().execute(itemsMusic.get(params[0]).getDetail()).get();
                mediaPlayer.setDataSource(urlLoaded);
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        proGress.dismiss();
                        mp.start();
                        ID_PLAY -= 1;
                        ID_CHECK_FIRST = ID_PLAY;
                        if (mp.isPlaying()) {
                            notification = new Runnable() {
                                public void run() {
                                    primarySeekBarProgressUpdater();
                                }
                            };
                            handler.postDelayed(notification, 1000);
                        } else {
                            //mSeekBar.setProgress(0);
                        }
                    }
                });
                mediaPlayer.setOnErrorListener(new OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        proGress.dismiss();
                        return false;
                    }
                });
                linkCurrent = urlLoaded;

            } catch (Exception e) {
                Log.e("privew music", "loi :" + e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
//            mButton.setImageResource(R.drawable.btn_pause);
            mButton.startAnimation(mAnim360);
            mTextView.setText(itemsMusic.get(id).getName());
        }

    }

    class playNextMusic extends AsyncTask<Integer, Void, Void> {
        @Override
        protected void onPreExecute() {
            proGress = new ProgressDialog(MainMusicActivity.this);
            proGress.setMessage("Đợi chút nhé ....");
            proGress.setCancelable(true);
            proGress.setCanceledOnTouchOutside(false);
            proGress.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    mediaPlayer.release();

                    mediaPlayer = new MediaPlayer();
//                    mButton.setImageResource(R.drawable.btn_play);
                    mButton.clearAnimation();
                    ID_CHECK_FIRST = -10000;
                    ID_PLAY = 2;
                    cancel(true);
                }
            });
            proGress.show();
        }

        @Override
        protected void onCancelled() {
            ansLoadURl.cancel(true);
        }

        @Override
        protected Void doInBackground(Integer... params) {
            if (isCancelled() == false) {
//                try {
                mediaPlayer.reset();
                String urlLoaded;
                try {
                    urlLoaded = ansLoadURl.execute(itemsMusic.get(params[0]).getDetail()).get();
                    linkCurrent = urlLoaded;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(linkCurrent);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                mediaPlayer.prepareAsync();
                //--- add new
                mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        proGress.dismiss();
                        ID_PLAY += 1;
                        ID_CHECK_FIRST = ID_PLAY;
                        mp.start();
                          /*  if (mp.isPlaying()) {
                                notification = new Runnable() {
                                    public void run() {
                                        primarySeekBarProgressUpdater();
                                    }
                                };
                                handler.postDelayed(notification, 1000);
                            } else {
                            }*/
                    }
                });
                mediaPlayer.setOnErrorListener(new OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        proGress.dismiss();
                        return false;
                    }
                });
               /* } catch (Exception e) {
                    Log.e("next music", "loi :" + e.toString());
                }*/
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        //mSeekBar.setSecondaryProgress(percent);

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mediaPlayer.reset();

    }

    // Load content list with Ansytask
    private class MyTask extends AsyncTask<String, Void, ArrayList<ItemsMusic>> {
        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainMusicActivity.this);
            pDialog.setMessage("Tải dữ liệu...");
            pDialog.setCancelable(true);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    mediaPlayer.reset();
                    cancel(true);
                }
            });
            pDialog.show();
        }

        @Override
        protected ArrayList<ItemsMusic> doInBackground(String... params) {
            mediaPlayer.reset();
            ArrayList<ItemsMusic> arrayResult = getData(params[0]);
            if (null != arrayResult && arrayResult.size() > 0) {
                publishProgress();

            }
            return arrayResult;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            //mTextView.setText(itemsMusic.get(0).getName());
        }

        @Override
        protected void onPostExecute(ArrayList<ItemsMusic> result) {
            Log.e("count item :", "" + result.size());
            if (null != pDialog && pDialog.isShowing()) {
                mTask.cancel(true);
                pDialog.cancel();
                pDialog.dismiss();
            }
            if (result != null && result.size() > 0) {
                mAdapter = new AdapterListMain(MainMusicActivity.this, R.drawable.ic_launcher, itemsMusic);
                mListView.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
            } else {
                AlertDialog.Builder mAlert = new AlertDialog.Builder(
                        MainMusicActivity.this);
                mAlert.setTitle("Không có dữ liệu");
                mAlert.setMessage(
                        "Đã xảy ra lỗi trong quá trình tải dữ liệu,Bạn có muốn tải lại không ?")
                        .setPositiveButton("Có",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        try {
                                            mTask = new MyTask();
                                            mTask.execute(DJ_LINK_PART + "1");
                                        } catch (Exception ex) {
                                            Log.e("error load", ex.toString());
                                        }
                                    }
                                })
                        .setNegativeButton("Không",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.cancel();
                                        dialog.dismiss();
                                        pDialog.cancel();
                                        pDialog.dismiss();
                                        mTask.cancel(true);
                                        finish();
                                    }
                                });
                AlertDialog mAlertDialog = mAlert.create();
                mAlertDialog.show();
            }
        }

    }


    public ArrayList<ItemsMusic> getData(String url) {
        try {
            String json = JsonParser.getJSONString(url);
            JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
            mJsonArray = object.getJSONArray(
                    ROOT_JSON);
            for (int i = 0; i < mJsonArray.length(); i++) {
                JSONObject objJson = mJsonArray.getJSONObject(i);
                //String nameSongs = objJson.getString(NAME).substring(0, 41) + "...";
                mItemsMusic.setName(objJson.getString(NAME));
                mItemsMusic.setDetail(objJson.getString(DETAIL));
                mItemsMusic.setId(objJson.getInt(ORDER));
                Random mNumberHearing = new Random();
                mItemsMusic.setHearing(String.valueOf(mNumberHearing.nextInt(10000)));
                Log.e("id", "" + objJson.getInt(ORDER));
                itemsMusic.add(mItemsMusic);
                //stringListMuic.
                mItemsMusic = new ItemsMusic();
            }
            ID_LIST_MAX = itemsMusic.size();
            Log.e("list max", "" + ID_LIST_MAX);
        } catch (Exception e) {
            Log.e("load data", e.toString());
        }
        return itemsMusic;
    }

    // get json url
    public String getURL(String urlDetail) {

        String json = JsonParser.getJSONString(urlDetail);
        if (null != json) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                mJsonArray = object.getJSONArray(
                        DETAIL_TAG_JSON);
                JSONObject objJson = mJsonArray.getJSONObject(0);
                return objJson.getString(URL);
            } catch (JSONException e) {
                Log.e("json", e.toString());
            }
        }
        return null;
    }

    class loadURL extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String json = JsonParser.getJSONString(params[0]);
            if (null != json) {
                try {
                    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                    mJsonArray = object.getJSONArray(
                            DETAIL_TAG_JSON);
                    JSONObject objJson = mJsonArray.getJSONObject(0);
                    return objJson.getString(URL);
                } catch (JSONException e) {
                    Log.e("json", e.toString());
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //new PlayMusicAnsytask().execute(result);
        }
    }

    class LoadMoreMusic extends AsyncTask<String, Void, ArrayList<ItemsMusic>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainMusicActivity.this);
            pDialog.setMessage("Update thêm nhạc..");
            pDialog.setCancelable(true);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					dialog.cancel();
					dialog.dismiss();
//					mLoadmore.cancel(true);
				}
			});
            pDialog.show();

        }
        @Override
        protected void onCancelled() {
        	super.onCancelled();
//        	mLoadmore.cancel(true);
        }
        @Override
        protected ArrayList<ItemsMusic> doInBackground(String... params) {
            //itemsMusic.clear();
            ArrayList<ItemsMusic> mListUpdate = getData(params[0]);
            // ID_LIST_MAX += mListUpdate.size();
            return mListUpdate;

        }

        @Override
        protected void onPostExecute(ArrayList<ItemsMusic> result) {
            if (null != result && isCancelled() == false) {
                currentPage += 1;
                int currentPosition = mListView.getFirstVisiblePosition();
                mAdapter = new AdapterListMain(MainMusicActivity.this, R.drawable.ic_launcher, itemsMusic);
                mListView.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                ID_LIST_MAX = result.size();
                Log.e("list load more ", "" + result.size());
                mListView.setSelectionFromTop(currentPosition + 1, 0);
                pDialog.dismiss();
            }

        }

    }

    /*
     * Download file music with string url
     */
    private class DownloadFile extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            proGress = new ProgressDialog(MainMusicActivity.this);
            proGress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            proGress.setMessage("Bài hát này đang được tải về ...");
            proGress.setCancelable(true);
            proGress.setIndeterminate(false);
            proGress.setMax(100);
            proGress.setProgress(0);
            proGress.show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... link) {
            int count;
            try {
                URL url = new URL(link[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conexion.getContentLength();
                Log.e("filelength = ", "" + lenghtOfFile);
                // downlod the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);
                OutputStream output = new FileOutputStream("/sdcard/" + link[1] + ".mp3");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            proGress.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            proGress.dismiss();
            super.onPostExecute(result);

        }
    }

    /*
     * Play music song with link url
     */
    private class PlayMusicAnsytask extends AsyncTask<String, Void, Void> {
        private boolean cancel = true;

        @Override
        protected void onPreExecute() {
            proGress = new ProgressDialog(MainMusicActivity.this);
            proGress.setMessage("Đang tải bài hát...");
            proGress.setCancelable(true);
            proGress.setCanceledOnTouchOutside(false);
            proGress.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    mediaPlayer.release();
                    mediaPlayer = new MediaPlayer();
//                    mButton.setImageResource(R.drawable.btn_play);
                    mButton.clearAnimation();
                    ID_CHECK_FIRST = -10000;
                    cancel(true);
                }
            });
            proGress.show();
        }

        @Override
        protected void onCancelled() {
            cancel = false;
        }

        @Override
        protected Void doInBackground(String... params) {
            //final String url = params[0];
            if (cancel == true && isCancelled() == false) {
                try {
                    mediaPlayer.reset();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mediaPlayer.setDataSource(params[0]);
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            proGress.dismiss();
                            mp.start();
                           /* if (mp.isPlaying()) {
                                //mSeekBar.setProgress((int)(((float)mp.getCurrentPosition()/mediaFileLengthInMilliseconds)*100));
                                notification = new Runnable() {
                                    public void run() {
                                        primarySeekBarProgressUpdater();
                                    }
                                };
                                handler.postDelayed(notification, 1000);
                            } else {
                                //mSeekBar.setProgress(0);
                            }*/
                        }
                    });
                    mediaPlayer.setOnErrorListener(new OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            proGress.dismiss();
                            return false;
                        }
                    });
                    mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
                    //primarySeekBarProgressUpdater();
                } catch (Exception e) {
                    Log.e("Error", e.toString());
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }

    public void itemMainClick(int position) {
        try {
            String urlLoaded = new loadURL().execute(itemsMusic.get(position).getDetail()).get();
            new PlayMusicAnsytask().execute(urlLoaded);
            mTextView.setText(itemsMusic.get(position).getName());
//            mButton.setImageResource(R.drawable.btn_pause);
            mButton.startAnimation(mAnim360);
            CHECK_CLICK = false;
//			ivFavorite.setImageResource(R.drawable.btnfavorite_like_up);
            linkCurrent = urlLoaded;
//            ID_PLAY = itemsMusic.get(position).getId();
            ID_PLAY = position;
            Log.e("ID_Check", "" + ID_PLAY);
            ID_CHECK_FIRST = itemsMusic.get(position).getId();
        } catch (Exception e) {
            Log.e("error main click", e.toString());
        }

    }

    //-------------------------------------------------------- Dang lam -------------------------------//
    public void NextSong(Boolean check) {
        if (check == true) {

        }
    }
    /*
     * Show gif image.
     */
    final Runnable mUpdateResults = new Runnable() {
    	        public void run() {
    	            if (mTmpBitmap != null && !mTmpBitmap.isRecycled()) {
    	            	mButton.setImageBitmap(mTmpBitmap);
    	            }
    	        }
    	    };
    public void playGif(InputStream stream) {
        mGifDecoder = new GifDecoder();
        mGifDecoder.read(stream);

        mIsPlayingGif = true;

        new Thread(new Runnable() {
            public void run() {
                final int n = mGifDecoder.getFrameCount();
                final int ntimes = mGifDecoder.getLoopCount();
                int repetitionCounter = 0;
                do {
                    for (int i = 0; i < n; i++) {
                        mTmpBitmap = mGifDecoder.getFrame(i);
                        int t = mGifDecoder.getDelay(i);
                        myHandler.post(mUpdateResults);
                        try {
                            Thread.sleep(t + 100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if(ntimes != 0) {
                        repetitionCounter ++;
                    }
                } while (mIsPlayingGif && (repetitionCounter <= ntimes));
            }
        }).start();
    }
    
    public void stopRendering() {
        mIsPlayingGif = true;
    }

    /*
     * Hanlder Event back in hard mobile
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        DialogQuitApp dialog = new DialogQuitApp(this) {
            @Override
            protected void onClickButtonDone() {
            	if(mediaPlayer.isPlaying()){
            		mediaPlayer.pause();
            		mediaPlayer.release();
            	}else{
            		mediaPlayer.release();
            	}
                finish();
            }
        };
        dialog.show(findViewById(R.id.root));
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(notification);
        myHandler.removeCallbacks(mUpdateResults);
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EasyTracker.getInstance(getApplicationContext()).activityStop(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EasyTracker.getInstance(getApplicationContext()).activityStart(this);
    }

}

